<?php
/**
 * 自定义字段函数
 */
defined('IN_IXDCW') or exit('Access Denied');
/**
 * Class AutoField
 */
class AutoField {

	/**
	 * 更新信息
	 * @param        $post_fields
	 * @param        $table
	 * @param        $itemid
	 * @param string $keyname
	 * @param array  $fd
	 * @return string
	 */
	public static function update($post_fields, $table, $itemid, $keyname = 'itemid', $fd = array()) {
		global $FD, $db;
		if (!$table || !$itemid) return '';
		if ($fd) $FD = $fd;
		$sql = '';
		foreach ($FD as $k => $v) {
			if (isset($post_fields[$v['name']]) || $v['html'] == 'checkbox') {
				$mk = $v['name'];
				$mv = $post_fields[$v['name']];
				if ($v['html'] == 'checkbox') $mv = implode(',', $post_fields[$v['name']]);
				$sql .= ",$mk='$mv'";
			}
		}
		$sql = substr($sql, 1);
		if ($sql) {
			if (self::getExtInfo($table, $itemid, $keyname)) {
				$doSql = "UPDATE {$table} SET $sql WHERE `$keyname`=$itemid";
				$db->query($doSql);
			} else {
				$post_fields[$keyname] = $itemid;
				$db->query(Sql::insert($table, $post_fields));
			}
		}
	}

	/**
	 * 获取扩展信息
	 * @param $table
	 * @param $keyid
	 * @param $keyname
	 * @return array|null
	 */
	public static function getExtInfo($table, $keyid, $keyname) {
		global $db;
		return $db->getOne("select * from {$table} where {$keyname}=$keyid");
	}

	/**
	 * 验证
	 * @param       $post_fields
	 * @param array $fd
	 */
	public static function check($post_fields, $fd = array()) {
		global $FD;
		include load('include.lang');
		if ($fd) $FD = $fd;
		Session::start();
		$uploads = isset($_SESSION['uploads']) ? $_SESSION['uploads'] : array();
		foreach ($FD as $k => $v) {
			$value = isset($post_fields[$v['name']]) ? $post_fields[$v['name']] : '';
			if (in_array($v['html'], array('thumb', 'file', 'editor')) && $uploads) {
				foreach ($uploads as $sk => $sv) {
					if ($v['html'] == 'editor') {
						if (strpos($value, $sv) !== false) unset($_SESSION['uploads'][$sk]);
					} else {
						if ($sv == $value) unset($_SESSION['uploads'][$sk]);
					}
				}
			}
			if (!$v['input_limit']) continue;
			if (!defined('DT_ADMIN') && !$v['front']) continue;
			if ($v['input_limit'] == 'is_date') {
				if (!is_date($value)) Prompt::message(lang($L['fields_input'], array($v['title'])));
			} else if ($v['input_limit'] == 'is_email') {
				if (!is_email($value)) Prompt::message(lang($L['fields_valid'], array($v['title'])));
			} else if (is_numeric($v['input_limit'])) {
				$length = Str::length($value);
				if ($length < $v['input_limit']) Prompt::message(lang($L['fields_less'], array($v['title'], $v['input_limit'])));
			} else {
				if (preg_match("/^([0-9]{1,})\-([0-9]{1,})$/", $v['input_limit'], $m)) {
					$length = Str::length($value);
					if ($m[1] && $length < $m[1]) Prompt::message(lang($L['fields_less'], array($v['title'], $m[1])));
					if ($m[2] && $length > $m[2]) Prompt::message(lang($L['fields_more'], array($v['title'], $m[2])));
				} else {
					if (!preg_match("/^" . $v['input_limit'] . "$/", $value)) Prompt::message(lang($L['fields_match'], array($v['title'])));
				}
			}
		}
	}

	/**
	 * JS信息
	 * @param array $fd
	 * @return string
	 */
	public static function js($fd = array()) {
		global $FD;
		if ($fd) $FD = $fd;
		$js = '';
		include load('include.lang');
		foreach ($FD as $k => $v) {
			if (!$v['input_limit']) continue;
			if (!defined('DT_ADMIN') && !$v['front']) continue;
			if ($v['input_limit'] == 'is_date') {
				$js .= 'f = "post_fields' . $v['name'] . '";l = Dd(f).value.length;';
				$js .= 'if(l != 10) {Dmsg("' . lang($L['fields_input'], array($v['title'])) . '", f, 1);return false;}';
			} else if ($v['input_limit'] == 'is_email') {
				$js .= 'f = "' . $v['name'] . '";l = Dd(f).value.length;';
				$js .= 'if(l < 8) {Dmsg("' . lang($L['fields_input'], array($v['title'])) . '", f);return false;}';
			} else if (is_numeric($v['input_limit'])) {
				if ($v['html'] == 'area') {
					$js .= 'f = "' . $v['name'] . '";l = Dd("areaid_1").value;';
					$js .= 'if(l == 0) {Dmsg("' . lang($L['fields_area']) . '", f);return false;}';
				} else {
					$js .= 'f = "' . $v['name'] . '";l = Dd(f).value.length;';
					$js .= 'if(l < ' . $v['input_limit'] . ') {Dmsg("' . lang($L['fields_less'], array($v['title'], $v['input_limit'])) . '", f);return false;}';
				}
			} else {
				if (preg_match("/^([0-9]{1,})\-([0-9]{1,})$/", $v['input_limit'], $m)) {
					$js .= 'f = "' . $v['name'] . '";l = Dd(f).value.length;';
					if ($m[1]) $js .= 'if(l < ' . $m[1] . ') {Dmsg("' . lang($L['fields_less'], array($v['title'], $m[1])) . '", f);return false;}';
					if ($m[2]) $js .= 'if(l > ' . $m[2] . ') {Dmsg("' . lang($L['fields_more'], array($v['title'], $m[2])) . '", f);return false;}';
				} else {
					$js .= 'f = "' . $v['name'] . '";l = Dd(f).value;';
					$js .= 'if(l.match(/^' . $v['input_limit'] . '$/) == null) {Dmsg("' . lang($L['fields_match'], array($v['title'])) . '", f);return false;}';
				}
			}
		}
		return $js;
	}

	/**
	 * 生成HTML
	 * @param string $left
	 * @param string $right
	 * @param array  $values
	 * @param array  $fd
	 * @return string
	 */
	public static function html($left = '<td class="tl">', $right = '<td>', $values = array(), $fd = array()) {
		extract($GLOBALS, EXTR_SKIP);
		if ($fd) $FD = $fd;
		$html = '';
		foreach ($FD as $k => $v) {
			if (!$v['display']) continue;
			if (!defined('DT_ADMIN') && !$v['front']) continue;
			$html .= self::show($k, $left, $right, $values, $fd);
		}
		return $html;
	}

	/**
	 * 生成单项目
	 * @param        $itemid
	 * @param string $left
	 * @param string $right
	 * @param array  $values
	 * @param array  $fd
	 * @return string
	 */
	public static function show($itemid, $left = '<td class="tl">', $right = '<td>', $values = array(), $fd = array()) {
		extract($GLOBALS, EXTR_SKIP);
		if ($fd) $FD = $fd;
		if (!$values) {
			if (isset($item)) $values = $item;
			if (isset($user)) $values = $user;
		}
		$html  = '';
		$v     = $FD[$itemid];
		$value = $v['default_value'];
		if (isset($values[$v['name']])) {
			$value = $values[$v['name']];
		} else if ($v['default_value']) {
			eval('$value = "' . $v['default_value'] . '";');
		}
		if ($v['html'] == 'hidden') {
			$html .= '<input type="hidden" name="post_fields[' . $v['name'] . ']" id="' . $v['name'] . '" value="' . $value . '" ' . $v['addition'] . '/>';
		} else {
			$html .= '<tr>' . $left;
			if ($v['input_limit']) {
				$html .= '<span class="f_red">*</span> ';
			} else {
				$html .= defined('DT_ADMIN') ? '<span class="f_hid">*</span> ' : '';
			}
			$html .= $v['title'];
			$html .= '</td>';
			$html .= $right;
			switch ($v['html']) {
				case 'text':
					$html .= '<input type="text" name="post_fields[' . $v['name'] . ']" id="' . $v['name'] . '" value="' . $value . '" ' . $v['addition'] . '/> <span class="f_red" id="d' . $v['name'] . '"></span>';
					break;
				case 'textarea':
					$html .= '<textarea name="post_fields[' . $v['name'] . ']" id="' . $v['name'] . '" ' . $v['addition'] . '>' . $value . '</textarea> <span class="f_red" id="d' . $v['name'] . '"></span>';
					break;
				case 'select':
					if ($v['option_value']) {
						$html .= '<select name="post_fields[' . $v['name'] . ']" id="' . $v['name'] . '" ' . $v['addition'] . '><option value="">' . $L['choose'] . '</option>';
						$rows = explode("*", $v['option_value']);
						foreach ($rows as $row) {
							if ($row) {
								$cols = explode("|", trim($row));
								$html .= '<option value="' . $cols[0] . '"' . ($cols[0] == $value ? ' selected' : '') . '>' . $cols[1] . '</option>';
							}
						}
						$html .= '</select> <span class="f_red" id="d' . $v['name'] . '"></span>';
					}
					break;
				case 'radio':
					if ($v['option_value']) {
						$html .= '<span id="' . $v['name'] . '">';
						$rows = explode("*", $v['option_value']);
						foreach ($rows as $rw => $row) {
							if ($row) {
								$cols = explode("|", trim($row));
								$html .= '<input type="radio" name="post_fields[' . $v['name'] . ']" value="' . $cols[0] . '" id="' . $v['name'] . '_' . $rw . '"' . ($cols[0] == $value ? ' checked' : '') . '> ' . $cols[1] . '&nbsp;&nbsp;&nbsp;';
							}
						}
						$html .= '</span> <span class="f_red" id="d' . $v['name'] . '"></span>';
					}
					break;
				case 'checkbox':
					if ($v['option_value']) {
						$html .= '<span id="' . $v['name'] . '">';
						$value = explode(',', $value);
						$rows  = explode("*", $v['option_value']);
						foreach ($rows as $rw => $row) {
							if ($row) {
								$cols = explode("|", trim($row));
								$html .= '<input type="checkbox" name="post_fields[' . $v['name'] . '][]" value="' . $cols[0] . '" id="' . $v['name'] . '_' . $rw . '"' . (in_array($cols[0], $value) ? ' checked' : '') . '> ' . $cols[1] . '&nbsp;&nbsp;&nbsp;';
							}
						}
						$html .= '</span> <span class="f_red" id="d' . $v['name'] . '"></span>';
					}
					break;
				case 'date':
					$html .= dcalendar('post_fields[' . $v['name'] . ']', $value);
					$html .= ' <span class="f_red" id="post_dfields' . $v['name'] . '"></span>';
					break;
				case 'thumb':
					$html .= Post::picture($moduleid, $v['name'], 'post_fields[' . $v['name'] . ']', $value, $v['width'], $v['height'], $v['addition']);
					break;
				case 'file':
					$html .= '<input name="post_fields[' . $v['name'] . ']" type="text" size="60" id="' . $v['name'] . '" value="' . $value . '" ' . $v['addition'] . '/>&nbsp;&nbsp;<span onclick="Dfile(' . $moduleid . ', Dd(\'' . $v['name'] . '\').value, \'' . $v['name'] . '\');" class="jt">[' . $L['upload'] . ']</span>&nbsp;&nbsp;<span onclick="if(Dd(\'' . $v['name'] . '\').value) window.open(Dd(\'' . $v['name'] . '\').value);" class="jt">[' . $L['preview'] . ']</span>';
					$html .= ' <span class="f_red" id="d' . $v['name'] . '"></span>&nbsp;&nbsp;<span onclick="Dd(\'' . $v['name'] . '\').value=\'\';" class="jt">[' . $L['delete'] . ']</span>';
					$html .= ' <span class="f_red" id="d' . $v['name'] . '"></span>';
					break;
				case 'editor':
					$toolbar = isset($GLOBALS['group_editor']) ? $GLOBALS['group_editor'] : 'Destoon';
					$html .= '<textarea name="post_fields[' . $v['name'] . ']" id="' . $v['name'] . '" style="display:none">' . $value . '</textarea><iframe id="' . $v['name'] . '___Frame" src="' . $MODULE[2]['linkurl'] . 'fckeditor/editor/fckeditor.html?InstanceName=' . $v['name'] . '&Toolbar=' . $toolbar . '" width="' . $v['width'] . '" height="' . $v['height'] . '" frameborder="no" scrolling="no"></iframe>';
					$html .= '<br/><span class="f_red" id="d' . $v['name'] . '"></span>';
					break;
				case 'level':
				case 'engine':
				case 'emission':
				case 'gearbox':
				case 'year':
				case 'country':
				case 'picture':
				case 'hang':
				case 'param_group':
					$treeFile = DT_CACHE . "/autoCategoryTree-{$v['html']}.php";
					if (file_exists($treeFile)) {
						$tree        = '<option value="0">请选择</option>';
						$treeContent = file_get_contents($treeFile);
						if ($value) {
							$preg        = "/(<option\s+value=\"{$value}\")/";
							$treeContent = preg_replace($preg, '$1 selected="selected"', $treeContent);
						}
						$tree .= $treeContent;
					} else {
						$tree = '<option value="0">尚未更新缓存,请更新缓存文件</option>';
					}
					$html .= '<select name="post_fields[' . $v['name'] . ']" id="' . $v['name'] . '" ' . $v['addition'] . '>';
					$html .= $tree;
					$html .= '<span class="f_red" id="d' . $v['name'] . '"></span>';
					break;
			}
			$html .= $v['note'];
			$html .= '</td></tr>';
		}
		return $html;
	}

	public static function values($var, $fd, $format = array()) {
		if (empty($format)) {
			$format = array(
				'select_empty' => '-',
				'radio_empty'  => '-', //   -无
				'radio_has'    => '●', // ●标配
				'radio_select' => '○', // ○选配
			);
		}
		$FD = array();
		foreach ($fd as $fv) {
			$FD[$fv['name']] = $fv;
		}
		$newVar = array();
		foreach ($var as $key => $val) {
			$newVar[$key] = isset($FD[$key]) ? self::value($FD[$key], $val, $format) : $val;
		}
		return $newVar;
	}

	public static function value($fdItem, $value, $format) {
		switch ($fdItem['html']) {
			case 'thumb':
				return '<img src="'.$value.'">';
				break;
			case 'text':
				if($value=="0"||!$value){
					return $format['select_empty'];
				}else{
					return $value;
				}
				break;
			case 'textarea':
			case 'date':
			case 'file':
			case 'editor':
				return $value;
				break;
			case 'checkbox':
			case 'select':
				$values       = explode(',', $value);
				$rows         = explode("*", $fdItem['option_value']);
				$returnValues = array();
				foreach ($values as $sv) {
					foreach ($rows as $row) {
						if ($row) {
							$cols = explode("|", trim($row));
							if (strpos($cols[1], '请选择') !== false) continue;
							if ($cols[0] == $sv) $returnValues[] = $cols[1];
						}
					}
				}
				if ($returnValues) {
					if($returnValues[0]=='是'){
						return $format['radio_has'];
					}else if($returnValues[0]=='无'){
						return $format['radio_empty'];
					}else if($returnValues[0]=='选装'){
						return $format['radio_select'];
					}else{
						return implode(',', $returnValues);
					}
				} else {
					return $format['select_empty'];
				}
				break;
			case 'radio':
				switch ($value) {
					case 0:
					return $format['radio_empty'];
					break;
					case 1:
						return $format['radio_has'];
						break;
					case 2:
						return $format['radio_select'];
						break;
				}
				if ($value == 0) {
					return $format['radio_empty'];
				}
				break;
			case 'level':
			case 'engine':
			case 'emission':
			case 'gearbox':
			case 'year':
			case 'country':
			case 'picture':
			case 'hang':
			case 'param_group':
				return AutoCategory::getCacheItem($fdItem['html'], $value);
				break;
		}
		return '';
	}

	/**
	 * 对字段的值进行处理
	 * @param $optionValue
	 * @return array
	 */
	public static function handleOptionValue($optionValue) {
		$arr    = explode('*', $optionValue);
		$return = array();
		foreach ($arr as $v) {
			$option             = explode('|', $v);
			$return[$option[0]] = $option[1];
		}
		return $return;
	}

}